﻿using System.Threading;
using JetBrains.Annotations;
using Missbot.AIModule.Base;
using Missbot.Core.Base;
using Missbot.Core.SyntaxChecker.ParamCheckers;

namespace Missbot.AIModule.Repeator
{
    /// <summary>
    /// 随机复读模块
    /// </summary>
    [UsedImplicitly]
    public class RepeatorMod : IAIModule
    {
        public override string Name => "随机复读";
        public override AIPriority Priority => AIPriority.Low;

        /// <summary>
        /// 随机复读频率
        /// </summary>
        private const long RepeatLimit = 30;

        /// <summary>
        /// 当前复读计数
        /// </summary>
        private long CurCount;

        /// <summary>
        /// 复读延迟时间
        /// </summary>
        private const int SleepTime = 2000;

        protected override bool OnInboxImpl(InboxSession session)
        {
            if (base.OnInboxImpl(session))
            {
                return true;
            }

            if (session.Group == null || session.Channel.BindingType != ChannelType.Messaging)
            {
                return false;
            }

            var checker = new UserParam();
            var checkResult = checker.Check(session.Text);
            if (checkResult.isValid)
            {
                return false;
            }

            CurCount++;
            if (CurCount < RepeatLimit)
            {
                return false;
            }

            CurCount %= RepeatLimit;
            Repeat(session);
            return true;
        }

        private static void Repeat(InboxSession session)
        {
            Thread.Sleep(SleepTime);

            session.SendBack(session.Text);
        }
    }
}